# coding: utf-8

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QLabel, QHBoxLayout, QVBoxLayout
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtGui import (
    QPixmap,
    QPainter,
    QPainterPath,
    QFont,
    QFontMetrics,
    QFontDatabase,
    QIcon,
    QImage,
)
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest

from qfluentwidgets import (
    CardWidget,
    PushButton,
    ToolTipFilter,
    ToolTipPosition,
    FluentIcon,
    NavigationItemPosition,
)

from app.view.resourceInfo_interface import ResourceDetailsInterface
from app.ui_controller.ui_pool import Portal_Pool, Ui_Pool


class ResourceCard(CardWidget):
    """资源展示卡片"""

    def __init__(
        self,
        coverPictureURL: str,
        resourceTitle: str,
        resourceAuthor: dict,
        resourceId: int,
        resourceRenewalTime: str,
        resourceSummary: str,
        parent=None,
    ):
        """
        __init__ 资源卡片初始化

        Args:
            coverPicture (QPixmap): 资源卡片图片
            resourceTitle (_type_): 资源标题
            resourceAuthor (_type_): 资源作者名称
            resourceId (_type_): 资源ID
            resourceRenewalTime (_type_): 资源更新时间
        """
        super().__init__(parent)

        # 信息初始化
        self.coverPictureURL: str = coverPictureURL
        self.resourceTitle: str = resourceTitle
        self.resourceAuthor: dict = resourceAuthor
        self.resourceId: int = resourceId
        self.resourceRenewalTime: str = resourceRenewalTime
        self.resourceSummary: str = resourceSummary

        # 组件初始化
        self.coverPictureLabel = QLabel(self)
        self.resourceTitleLabel = QLabel(self)
        self.resourceAuthorNameLabel = QLabel(self)
        self.resourceApprovalPictureLabel = QLabel(self)
        self.resourceRenewalTimeLabel = QLabel(self)
        self.resourcePurchaseButton = PushButton(self)

        self.__initWidget()
        self._loadImage(self.coverPictureURL)

    def __initWidget(self):
        self.setFixedSize(190, 260)
        self.setStyleSheet("color: #1D1D1F")
        self.setBorderRadius(8)
        # 资源图片
        self.coverPictureLabel.setFixedSize(177, 100)
        self.coverPictureLabel.setScaledContents(True)
        # self.setRoundedImage(self.coverPictureLabel, self.coverPicture, 10)

        # 资源标题
        self.resourceTitleLabel.setText(self.resourceTitle)
        self.resourceTitleLabel.setAlignment(
            Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
        )
        self.resourceTitleLabel.setFixedSize(180, 28)
        self.resourceTitleLabel.setFont(self._setFont("HarmonyOS Sans SC", 18))
        self.resourceTitleLabel.setWordWrap(True)
        fontWidth = QFontMetrics(self.resourceTitleLabel.font())
        elideNote = fontWidth.elidedText(
            self.resourceTitle, Qt.ElideRight, self.resourceTitleLabel.width()
        )
        self.resourceTitleLabel.setText(elideNote)
        self.resourceTitleLabel.setToolTip(self.resourceTitle)
        self.resourceTitleLabel.installEventFilter(
            ToolTipFilter(self.resourceTitleLabel, 0, ToolTipPosition.BOTTOM)
        )

        # 资源作者
        self.resourceAuthorNameLabel.setText(self.resourceAuthor["Name"])
        self.resourceAuthorNameLabel.setFont(self._setFont("HarmonyOS Sans SC", 15))
        fontWidth = QFontMetrics(self.resourceAuthorNameLabel.font())
        elideNote = fontWidth.elidedText(
            self.resourceAuthor["Name"],
            Qt.TextElideMode.ElideRight,
            self.resourceAuthorNameLabel.width(),
        )
        self.resourceAuthorNameLabel.setText(elideNote)
        self.resourceAuthorNameLabel.setToolTip(self.resourceAuthor["Name"])
        self.resourceAuthorNameLabel.installEventFilter(
            ToolTipFilter(self.resourceAuthorNameLabel, 0, ToolTipPosition.BOTTOM)
        )

        # 更新日期
        self.resourceRenewalTimeLabel.setText(self.resourceRenewalTime)
        self.resourceRenewalTimeLabel.setFont(self._setFont("HarmonyOS Sans SC", 10))

        # 查看按钮
        self.resourcePurchaseButton.setText(self.tr("view details"))
        self.resourcePurchaseButton.setIcon(FluentIcon.APPLICATION)
        self.resourcePurchaseButton.clicked.connect(self._buttonClicked)

        self.__initLayout()

    def __initLayout(self):
        self.layouts = QVBoxLayout(self)
        self.layouts.setSpacing(0)
        self.layouts.setContentsMargins(5, 5, 5, 5)
        self.setLayout(self.layouts)
        self.authorLayout = QHBoxLayout()

        self.layouts.addWidget(
            self.coverPictureLabel,
            0,
            Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter,
        )
        self.layouts.addSpacing(5)
        self.layouts.addWidget(
            self.resourceTitleLabel,
            0,
            Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter,
        )

        self.authorLayout.addWidget(
            self.resourceAuthorNameLabel,
            0,
            Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
        )

        self.layouts.addLayout(self.authorLayout)

        self.layouts.addWidget(
            self.resourceRenewalTimeLabel,
            0,
            Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft,
        )
        self.layouts.addWidget(
            self.resourcePurchaseButton,
            0,
            Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter,
        )

    def setRoundedImage(self, label, pixmap, radius):
        pixmap = pixmap.scaled(
            label.size(), Qt.AspectRatioMode.KeepAspectRatioByExpanding
        )

        rounded_pixmap = QPixmap(pixmap.size())
        rounded_pixmap.fill(Qt.transparent)

        painter = QPainter(rounded_pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        path = QPainterPath()
        path.addRoundedRect(0, 0, pixmap.width(), pixmap.height(), radius, radius)
        painter.setClipPath(path)
        painter.drawPixmap(0, 0, pixmap)
        painter.end()

        label.setPixmap(rounded_pixmap)
        label.setScaledContents(True)

    def _setFont(self, fontFamily, fontSize):
        font = QFont()
        font.setFamily(fontFamily)
        font.setPointSize(fontSize)
        return font

    # 网络线程加载图片
    # TODO: 优化流程
    def _loadImage(self, url):
        # 创建QNetworkAccessManager实例
        self.manager = QNetworkAccessManager(self)
        # 连接信号
        self.manager.finished.connect(self._imageLoaded)

        # 创建QNetworkRequest
        request = QNetworkRequest(QUrl(url))

        # 发送GET请求
        self.manager.get(request)

    def _imageLoaded(self, reply):
        # 检查请求是否成功
        if reply.error() == QNetworkReply.NoError:
            # 将网络回复转换为QImage
            image = QImage()
            image.loadFromData(reply.readAll())
            # 将QImage转换为QPixmap并设置到QLabel
            self.setRoundedImage(self.coverPictureLabel, QPixmap.fromImage(image), 8)
        else:
            self.setRoundedImage(
                self.coverPictureLabel, QPixmap(":app/images/notFind.png"), 8
            )

    def _buttonClicked(self):
        main_pool: Ui_Pool = Portal_Pool.portals["main_pool"]

        win = main_pool.find_object_byName("win")
        infoInterface = ResourceDetailsInterface(
            self.coverPictureLabel.pixmap(),
            self.resourceTitle,
            self.resourceAuthor,
            self.resourceId,
            self.resourceRenewalTime,
            self.resourceSummary,
            win,
        )
        infoInterface.setObjectName(f"tempInterface_{self.resourceId}")
        icon = QIcon(self.coverPictureLabel.pixmap())

        win.addInterface(
            infoInterface,
            icon,
            self.resourceTitle,
            NavigationItemPosition.SCROLL,
        )
        win.navigationInterface.setCurrentItem(f"tempInterface_{self.resourceId}")
        win.stackedWidget.setCurrentWidget(infoInterface)
